package com.analyse.stock.strategy.indicator;

import org.ta4j.core.Indicator;
import org.ta4j.core.indicators.SMAIndicator;
import org.ta4j.core.num.Num;

/**
 * SMA Slope Indicator.
 */
public class SMASlopeIndicator implements Indicator<Num> {
    private final SMAIndicator smaIndicator; // SMA 指标
    private final int slopePeriod; // 斜率计算的时间间隔

    public SMASlopeIndicator(Indicator<Num> indicator, int smaPeriod, int slopePeriod) {
        this.smaIndicator = new SMAIndicator(indicator, smaPeriod);
        this.slopePeriod = slopePeriod;
    }

    @Override
    public Num getValue(int index) {
        if (index < slopePeriod) {
            // 如果数据不足以计算斜率，返回 0
            return smaIndicator.numOf(0);
        }
        // 当前点的 SMA 值
        Num currentSMA = smaIndicator.getValue(index);
        // 前 slopePeriod 点的 SMA 值
        Num previousSMA = smaIndicator.getValue(index - slopePeriod);
        // 计算斜率
        return currentSMA.minus(previousSMA).dividedBy(numOf(slopePeriod));
    }

    @Override
    public org.ta4j.core.BarSeries getBarSeries() {
        return smaIndicator.getBarSeries();
    }

    @Override
    public Num numOf(Number number) {
        return smaIndicator.getBarSeries().numOf(number);
    }
}
